import React, { useContext, useMemo } from 'react'
import Myback from './conponents/Myback'
import { Tabs, ProductCard, Tag, Button, Space, Toast } from 'react-vant'
import Ctx from '../store/Ctx'
import { Star, StarO } from '@react-vant/icons';
import '../App.css'
import { useState } from 'react';

export default function Home(props) {

  let obj = useContext(Ctx)
  //console.log(obj);
  //定义一个状态
  let [index, setIndex] = useState(0)

  let newlist = useMemo(() => {
    return obj.datalist.filter(item => {
      if (index == 0) return item
      return item.typeId === index
    })
  }, [index, obj.datalist])

  return (
    <div>

      {/* 导航栏 */}
      <Myback title={'首页'} leftText={false}></Myback>

      {/* 标签页 tap切换类型 */}
      <Tabs onChange={(e) => {
        setIndex(e)

      }}>
        {['全部', '推荐', '小说', '儿童'].map(item => (
          <Tabs.TabPane key={item} title={item} />
        ))}
      </Tabs>

      {/* 渲染数据 列表 */}
      <div className='homelist'>
        {
          newlist.map(item => {
            return <ProductCard
              onClick={() => {
                //跳转并传参
                props.history.push({
                  pathname: '/details',
                  state: item.id
                })
              }}
              key={item.id}
              num={<>
                <Space>
                  <span style={{ position: 'relative', top: '5px' }}
                    onClick={(e) => {
                      //阻止事件冒泡
                      e.stopPropagation()
                      if (item.collec) {
                        Toast.info('取消收藏')
                      } else {
                        Toast.info('收藏成功')
                      }
                      //切换收藏的状态
                      obj.dispatch({
                        type: 'change_collec',
                        payload: item.id
                      })
                    }} >
                    {<Star fontSize={16} color={item.collec ? 'red' : ''} />}
                  </span>
                  <Button size='mini' round type={item.sub ? 'warning' : 'default'}
                    onClick={(e) => {
                      //阻止事件冒泡
                      e.stopPropagation()
                      //切换订阅的状态
                      if (item.sub) {
                        Toast.info('取消订阅')
                      } else {
                        Toast.info('订阅成功')
                      }
                      obj.dispatch({
                        type: 'change_sub',
                        payload: item.id
                      })
                    }}>
                    {item.sub ? '已经订阅' : '免费订阅'}
                  </Button>
                </Space>
              </>}
              desc={item.ms}
              title={item.title}
              thumb={item.img}
            />
          })
        }
      </div>


    </div>
  )
}
